package com.xgc.erp.info.entity.ctrl;

import com.jfinal.aop.Inject;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.xgc.common.base.BaseController;
import com.xgc.common.config.Constan;
import com.xgc.common.config.WebContant;
import com.xgc.common.kit.IdKit;
import com.xgc.common.model.Entity;
import com.xgc.common.model.EntityImg;
import com.xgc.common.util.IdWorker;
import com.xgc.common.visit.Visitor;
import com.xgc.common.vo.Feedback;
import com.xgc.common.vo.TreeNode;
import com.xgc.erp.info.entity.service.EntityImgService;
import com.xgc.erp.info.entity.service.EntityService;

import java.io.*;
import java.net.URLDecoder;
import java.util.*;

//@ControllerBind(path="/erp/info/entity")
public class EntityController extends BaseController {
    @Inject
    private EntityService service;
    @Inject
    private EntityImgService imgService;

    public void index() {
        render("index.html");
    }

    public void list(){
        Record record = new Record();
        String parId = getPara("par_id");

        if(parId == null || parId.equals("")){
            String sql = Db.getSql("erp.getEntityRootTree");
            renderJson(service.queryForListEq(sql,getParaToInt("pageNumber",1), getParaToInt("pageSize",10),record,"order by create_time desc"));
            return ;
        }
        record.set("par_entity", parId);
        renderJson(service.queryForList(getParaToInt("pageNumber",1), getParaToInt("pageSize",10),record,"order by create_time desc"));
    }

    /**
     * 物品关系树
     *
     * @author QinHaiLin
     * @date 2018年10月9日
     */
    public void entityTree() {
        Collection<TreeNode> nodeList = this.service.getEntityTree(null);
        Collection<TreeNode> nodes = new ArrayList<TreeNode>();
        TreeNode node = new TreeNode();
        node.setId("");
        node.setText(WebContant.projectName);
        node.setChildren(nodeList);
        nodes.add(node);

        renderJson(nodes);
    }

    public void add() {
        String parEntity = getPara("par_entity");
        setAttr("par_entity", parEntity);
        Entity parent = (Entity) service.findById(parEntity);
        setAttr("parent", parent);
        render("add.html");
    }

    public void save() {
        Entity entity=getBean(Entity.class);
        String entityId = IdKit.getLocalTrmSeqNum();
        entity.setEntityId(entityId);
        Visitor vs = getVisitor();
        entity.setCreator(vs.getCode());
        entity.setCreateTime(new Date());
        boolean  flag = service.save(entity);
        if(!flag) {
            setException("保存失败");
        }
        render("add.html");
    }

    public void edit() throws UnsupportedEncodingException {
        Entity entity =(Entity) service.findById(URLDecoder.decode(getPara("primaryKey"),"utf-8"));
        Entity parent = (Entity) service.findById(entity.getParEntity()==null?"":entity.getParEntity().toString());
        setAttr("entity", entity);
        setAttr("parent", parent);
        render("edit.html");
    }

    public void update() {
        Entity entity=getBean(Entity.class);
        Visitor vs = getVisitor();
        entity.setModifier(vs.getCode());
        entity.setUpdateTime(new Date());
        service.update(entity);
        setAttr("entity", entity);
        render("edit.html");
    }

    public void delete() {
        service.deleteByIds(getIds());
        renderJson(Feedback.success());
    }

    public void getParent(){
        Record record = service.getParentEntity(getInt("entityId"));
        renderJson(record);
    }

    public void getInfo(){
        String entityId = get("entityId");
        Entity entity = (Entity) service.findById(entityId);
        renderJson(entity);
    }

    public void review(){
        String id = getPara("img_id");
        EntityImg img =(EntityImg) imgService.findById(id);
        String imageUrl = img.getImgUrl();

        if(imageUrl==null||imageUrl.equals("")){
            renderHtml("<img src=\"/static/img/error/error.png\">");
            return;
        }

        try {
            String url_path = imageUrl;
            File image = new File(url_path);
            @SuppressWarnings("resource")
            FileInputStream inputStream = new FileInputStream(image);
            int length = inputStream.available();
            byte data[] = new byte[length];
            getResponse().setContentLength(length);
            String fileName = image.getName();
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            getResponse().setContentType(imageContentType.get(fileType));
            inputStream.read(data);
            OutputStream toClient = getResponse().getOutputStream();
            toClient.write(data);
            toClient.flush();
            toClient.close();
        } catch (IOException e) {
            handerException(e);
            renderHtml("<img src=\"/static/img/error/error.png\">");
            return;
        }
        renderNull();
    }

    private static Map<String, String> imageContentType = new HashMap<String, String>();
    static {
        imageContentType.put("jpg","image/jpeg");
        imageContentType.put("jpeg","image/jpeg");
        imageContentType.put("png","image/png");
        imageContentType.put("tif","image/tiff");
        imageContentType.put("tiff","image/tiff");
        imageContentType.put("ico","image/x-icon");
        imageContentType.put("bmp","image/bmp");
        imageContentType.put("gif","image/gif");
    }

    /**
     * 跳转至上传页面
     *
     */
    public void toImgUpload() {
        String objectId = getPara();
        if (objectId == null) {
            objectId = getVisitor().getCode();
        }
        String entityId = getPara("entity_id");
        Entity entity = (Entity) service.findById(entityId);
        setAttr("entityCode",entity.getEntityCode());
        setAttr("objectId", objectId);
        render("imgList.html");
    }

    /**
     * 上传文件,可多附件上传
     *
     */
    public void upload() {
        List<UploadFile> uploadList = getFiles();
        String vs = getVisitor().getCode();
        String entityCode = getPara("entityCode");
        List<String> url = imgService.saveFiles(uploadList, vs, entityCode);
        renderJson(Ret.ok("url", url));
    }

    /**
     * 文件列表
     */
    public void imgList(){
        String entityCode = getPara("entityCode");
        Record record = new Record();
        record.set("entity_code", entityCode);
        renderJson(imgService.queryForListEq(getParaToInt("pageNumber",1), getParaToInt("pageSize",10),record,"order by create_time desc"));
    }

    public void renderEntityTree(){
        render("entityTree.html");
    }

}
